<template>
  <div class="message-center">
    <el-card class="message-card">
      <!-- 搜索工具栏 -->
      <div class="search-toolbar">
        <div class="search-left">
          <el-input
            v-model="searchQuery"
            placeholder="搜索消息标题/内容"
            class="search-input"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-button type="primary" @click="showAdvancedSearch = !showAdvancedSearch">
            <el-icon><Filter /></el-icon>
            高级搜索
          </el-button>
        </div>
        <div class="search-right">
          <el-button-group>
            <el-button :type="viewMode === 'list' ? 'primary' : ''" @click="viewMode = 'list'">
              <el-icon><List /></el-icon>
            </el-button>
            <el-button :type="viewMode === 'category' ? 'primary' : ''" @click="viewMode = 'category'">
              <el-icon><Grid /></el-icon>
            </el-button>
          </el-button-group>
        </div>
      </div>

      <!-- 高级搜索表单 -->
      <el-collapse-transition>
        <div v-show="showAdvancedSearch" class="advanced-search">
          <el-form :model="advancedSearchForm" label-width="80px" class="search-form">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="消息类型">
                  <el-select v-model="advancedSearchForm.type" placeholder="请选择" clearable>
                    <el-option
                      v-for="item in messageTypes"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="标签">
                  <el-select v-model="advancedSearchForm.tags" multiple placeholder="请选择" clearable>
                    <el-option
                      v-for="item in tagOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="状态">
                  <el-select v-model="advancedSearchForm.status" placeholder="请选择" clearable>
                    <el-option label="未读" value="unread" />
                    <el-option label="已读" value="read" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="16">
                <el-form-item label="时间范围">
                  <el-date-picker
                    v-model="advancedSearchForm.timeRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item>
                  <el-button type="primary" @click="handleAdvancedSearch">搜索</el-button>
                  <el-button @click="resetAdvancedSearch">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-collapse-transition>

      <!-- 消息列表视图 -->
      <div v-if="viewMode === 'list'" class="message-list">
        <div class="list-toolbar">
          <div class="left">
            <el-checkbox
              v-model="selectAll"
              :indeterminate="isIndeterminate"
              @change="handleSelectAllChange"
            >
              全选
            </el-checkbox>
            <el-button-group>
              <el-button @click="handleBatchRead" :disabled="!selectedMessages.length">
                标记已读
              </el-button>
              <el-button @click="handleBatchDelete" :disabled="!selectedMessages.length">
                删除
              </el-button>
            </el-button-group>
          </div>
          <div class="right">
            <el-button @click="handleExport">
              <el-icon><Download /></el-icon>
              导出
            </el-button>
          </div>
        </div>

        <el-table
          ref="messageTable"
          :data="messageList"
          border
          v-loading="loading"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column type="expand">
            <template #default="props">
              <div class="message-detail">
                <div class="detail-content" v-html="props.row.content"></div>
                <div class="detail-meta">
                  <div class="meta-item">
                    <span class="label">发送时间：</span>
                    <span>{{ props.row.sendTime }}</span>
                  </div>
                  <div class="meta-item">
                    <span class="label">发送人：</span>
                    <span>{{ props.row.sender }}</span>
                  </div>
                  <div class="meta-item">
                    <span class="label">标签：</span>
                    <el-tag
                      v-for="tag in props.row.tags"
                      :key="tag"
                      size="small"
                      class="message-tag"
                    >
                      {{ tag }}
                    </el-tag>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="title" label="标题" min-width="200">
            <template #default="scope">
              <div class="message-title">
                <el-tag
                  v-if="!scope.row.isRead"
                  type="danger"
                  size="small"
                  class="unread-tag"
                >未读</el-tag>
                <span>{{ scope.row.title }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="type" label="类型" width="120">
            <template #default="scope">
              <el-tag :type="getTypeTagType(scope.row.type)">
                {{ getTypeLabel(scope.row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="sendTime" label="发送时间" width="180" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button
                v-if="!scope.row.isRead"
                type="primary"
                link
                @click="handleRead(scope.row)"
              >
                标记已读
              </el-button>
              <el-button
                type="primary"
                link
                @click="handleForward(scope.row)"
              >
                转发
              </el-button>
              <el-button
                type="danger"
                link
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分类视图 -->
      <div v-else class="message-category">
        <el-tabs v-model="activeCategory" @tab-click="handleCategoryChange">
          <el-tab-pane
            v-for="category in categories"
            :key="category.value"
            :label="category.label"
            :name="category.value"
          >
            <div class="category-content">
              <div class="category-header">
                <h3>{{ category.label }}</h3>
                <div class="category-stats">
                  <span>未读：{{ category.unread }}</span>
                  <span>总计：{{ category.total }}</span>
                </div>
              </div>
              <el-row :gutter="20">
                <el-col
                  v-for="message in categoryMessages"
                  :key="message.id"
                  :span="8"
                >
                  <el-card
                    class="message-card"
                    :class="{ 'is-unread': !message.isRead }"
                    shadow="hover"
                  >
                    <template #header>
                      <div class="card-header">
                        <el-tag
                          v-if="!message.isRead"
                          type="danger"
                          size="small"
                        >未读</el-tag>
                        <span class="title">{{ message.title }}</span>
                      </div>
                    </template>
                    <div class="card-content">
                      <div class="content-preview">{{ message.content }}</div>
                      <div class="card-meta">
                        <span class="time">{{ message.sendTime }}</span>
                        <div class="actions">
                          <el-button
                            v-if="!message.isRead"
                            type="primary"
                            link
                            @click="handleRead(message)"
                          >
                            标记已读
                          </el-button>
                          <el-button
                            type="primary"
                            link
                            @click="handleForward(message)"
                          >
                            转发
                          </el-button>
                          <el-button
                            type="danger"
                            link
                            @click="handleDelete(message)"
                          >
                            删除
                          </el-button>
                        </div>
                      </div>
                    </div>
                  </el-card>
                </el-col>
              </el-row>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 转发消息对话框 -->
    <el-dialog
      v-model="forwardDialogVisible"
      title="转发消息"
      width="500px"
    >
      <el-form :model="forwardForm" label-width="80px">
        <el-form-item label="接收者">
          <el-select
            v-model="forwardForm.receivers"
            multiple
            filterable
            remote
            :remote-method="searchUsers"
            :loading="userSearchLoading"
            placeholder="请选择接收者"
          >
            <el-option
              v-for="item in userOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <span>{{ item.name }}</span>
              <span class="user-info">{{ item.department }} - {{ item.position }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="转发说明">
          <el-input
            v-model="forwardForm.comment"
            type="textarea"
            :rows="3"
            placeholder="请输入转发说明（选填）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="forwardDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmForward" :loading="forwarding">
          确认转发
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Filter,
  List,
  Grid,
  Download
} from '@element-plus/icons-vue'
import {
  getMessageList,
  getMessageDetail,
  markMessageRead,
  deleteMessage,
  forwardMessage,
  exportMessages,
  searchUsers,
  getUnreadCount
} from '@/api/message'
import wsClient from '@/utils/websocket'

// 视图模式
const viewMode = ref('list')
const showAdvancedSearch = ref(false)
const loading = ref(false)
const userSearchLoading = ref(false)

// 分页数据
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索相关
const searchQuery = ref('')
const advancedSearchForm = reactive({
  type: '',
  tags: [],
  status: '',
  timeRange: []
})

// 消息类型
const messageTypes = [
  { label: '系统通知', value: 'system' },
  { label: '业务通知', value: 'business' },
  { label: '营销通知', value: 'marketing' },
  { label: '活动通知', value: 'activity' }
]

// 标签选项
const tagOptions = [
  { label: '重要', value: 'important' },
  { label: '紧急', value: 'urgent' },
  { label: '普通', value: 'normal' }
]

// 分类数据
const categories = [
  { label: '全部消息', value: 'all', unread: 0, total: 0 },
  { label: '系统通知', value: 'system', unread: 0, total: 0 },
  { label: '业务通知', value: 'business', unread: 0, total: 0 },
  { label: '营销通知', value: 'marketing', unread: 0, total: 0 },
  { label: '活动通知', value: 'activity', unread: 0, total: 0 }
]
const activeCategory = ref('all')

// 消息列表
const messageList = ref([])
const messageTable = ref(null)
const selectedMessages = ref([])
const selectAll = ref(false)
const isIndeterminate = ref(false)

// 转发相关
const forwardDialogVisible = ref(false)
const forwarding = ref(false)
const forwardForm = reactive({
  messageId: null,
  receivers: [],
  comment: ''
})
const userOptions = ref([])

// 计算当前分类的消息
const categoryMessages = computed(() => {
  if (activeCategory.value === 'all') {
    return messageList.value
  }
  return messageList.value.filter(msg => msg.type === activeCategory.value)
})

// 初始化数据
onMounted(() => {
  fetchMessageList()
  // 连接WebSocket
  wsClient.connect()
  // 添加消息处理器
  wsClient.addMessageHandler(handleWebSocketMessage)
})

// 获取消息列表
const fetchMessageList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      query: searchQuery.value,
      ...advancedSearchForm,
      startTime: advancedSearchForm.timeRange?.[0],
      endTime: advancedSearchForm.timeRange?.[1]
    }
    const res = await getMessageList(params)
    messageList.value = res.data.list
    total.value = res.data.total
    
    // 更新分类统计
    updateCategoryStats(res.data.stats)
  } catch (error) {
    console.error('获取消息列表失败:', error)
    ElMessage.error('获取消息列表失败')
  } finally {
    loading.value = false
  }
}

// 更新分类统计
const updateCategoryStats = (stats) => {
  categories.forEach(category => {
    if (category.value === 'all') {
      category.unread = stats.totalUnread
      category.total = stats.total
    } else {
      const categoryStat = stats.categories.find(s => s.type === category.value)
      if (categoryStat) {
        category.unread = categoryStat.unread
        category.total = categoryStat.total
      }
    }
  })
}

// 搜索处理
const handleSearch = () => {
  pageNum.value = 1
  fetchMessageList()
}

// 高级搜索
const handleAdvancedSearch = () => {
  pageNum.value = 1
  fetchMessageList()
}

// 重置高级搜索
const resetAdvancedSearch = () => {
  Object.assign(advancedSearchForm, {
    type: '',
    tags: [],
    status: '',
    timeRange: []
  })
  handleAdvancedSearch()
}

// 分类切换
const handleCategoryChange = () => {
  pageNum.value = 1
  fetchMessageList()
}

// 选择处理
const handleSelectionChange = (selection) => {
  selectedMessages.value = selection
  const checkedCount = selection.length
  selectAll.value = checkedCount === messageList.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < messageList.value.length
}

const handleSelectAllChange = (val) => {
  messageTable.value.toggleAllSelection()
  isIndeterminate.value = false
}

// 批量操作
const handleBatchRead = async () => {
  try {
    await markMessageRead(selectedMessages.value.map(msg => msg.id))
    ElMessage.success('标记已读成功')
    fetchMessageList()
  } catch (error) {
    console.error('标记已读失败:', error)
    ElMessage.error('标记已读失败')
  }
}

const handleBatchDelete = () => {
  ElMessageBox.confirm('确定要删除选中的消息吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteMessage(selectedMessages.value.map(msg => msg.id))
      ElMessage.success('删除成功')
      fetchMessageList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 单个消息操作
const handleRead = async (message) => {
  try {
    await markMessageRead([message.id])
    ElMessage.success('标记已读成功')
    fetchMessageList()
  } catch (error) {
    console.error('标记已读失败:', error)
    ElMessage.error('标记已读失败')
  }
}

const handleDelete = (message) => {
  ElMessageBox.confirm('确定要删除该消息吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteMessage([message.id])
      ElMessage.success('删除成功')
      fetchMessageList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 转发消息
const handleForward = (message) => {
  forwardForm.messageId = message.id
  forwardForm.receivers = []
  forwardForm.comment = ''
  forwardDialogVisible.value = true
}

const searchUsers = async (query) => {
  if (query) {
    userSearchLoading.value = true
    try {
      const res = await searchUsers({ keyword: query })
      userOptions.value = res.data
    } catch (error) {
      console.error('搜索用户失败:', error)
    } finally {
      userSearchLoading.value = false
    }
  }
}

const confirmForward = async () => {
  if (!forwardForm.receivers.length) {
    ElMessage.warning('请选择接收者')
    return
  }

  forwarding.value = true
  try {
    await forwardMessage(forwardForm)
    ElMessage.success('转发成功')
    forwardDialogVisible.value = false
  } catch (error) {
    console.error('转发失败:', error)
    ElMessage.error('转发失败')
  } finally {
    forwarding.value = false
  }
}

// 导出消息
const handleExport = async () => {
  try {
    const params = {
      query: searchQuery.value,
      ...advancedSearchForm,
      startTime: advancedSearchForm.timeRange?.[0],
      endTime: advancedSearchForm.timeRange?.[1]
    }
    await exportMessages(params)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchMessageList()
}

const handleCurrentChange = (val) => {
  pageNum.value = val
  fetchMessageList()
}

// 工具函数
const getTypeTagType = (type) => {
  const types = {
    system: '',
    business: 'success',
    marketing: 'warning',
    activity: 'info'
  }
  return types[type] || ''
}

const getTypeLabel = (type) => {
  const item = messageTypes.find(t => t.value === type)
  return item ? item.label : type
}

// WebSocket消息处理
const handleWebSocketMessage = (message) => {
  if (message.type === 'notification') {
    // 收到新消息，刷新列表
    fetchMessageList()
    // 显示消息提醒
    ElMessage({
      type: 'info',
      message: `收到新消息：${message.title}`,
      duration: 3000
    })
  }
}

// 组件卸载时断开WebSocket
onUnmounted(() => {
  // 移除消息处理器
  wsClient.removeMessageHandler(handleWebSocketMessage)
  // 断开WebSocket连接
  wsClient.disconnect()
})
</script>

<style lang="scss" scoped>
.message-center {
  padding: 20px;

  .message-card {
    .search-toolbar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .search-left {
        display: flex;
        gap: 10px;

        .search-input {
          width: 300px;
        }
      }
    }

    .advanced-search {
      margin-bottom: 20px;
      padding: 20px;
      background-color: #f5f7fa;
      border-radius: 4px;

      .search-form {
        .el-form-item {
          margin-bottom: 0;
        }
      }
    }

    .message-list {
      .list-toolbar {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;

        .left {
          display: flex;
          align-items: center;
          gap: 10px;
        }
      }

      .message-detail {
        padding: 20px;

        .detail-content {
          margin-bottom: 15px;
          line-height: 1.6;
        }

        .detail-meta {
          color: #909399;
          font-size: 13px;

          .meta-item {
            margin-bottom: 5px;

            .label {
              margin-right: 5px;
            }

            .message-tag {
              margin-right: 5px;
            }
          }
        }
      }

      .message-title {
        display: flex;
        align-items: center;
        gap: 8px;

        .unread-tag {
          flex-shrink: 0;
        }
      }
    }

    .message-category {
      .category-content {
        .category-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 20px;

          h3 {
            margin: 0;
          }

          .category-stats {
            color: #909399;
            font-size: 13px;

            span {
              margin-left: 15px;
            }
          }
        }

        .message-card {
          margin-bottom: 20px;
          transition: all 0.3s;

          &.is-unread {
            border-color: #f56c6c;
          }

          .card-header {
            display: flex;
            align-items: center;
            gap: 8px;

            .title {
              flex: 1;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }

          .card-content {
            .content-preview {
              margin-bottom: 10px;
              color: #606266;
              font-size: 13px;
              line-height: 1.5;
              height: 40px;
              overflow: hidden;
              text-overflow: ellipsis;
              display: -webkit-box;
              -webkit-line-clamp: 2;
              -webkit-box-orient: vertical;
            }

            .card-meta {
              display: flex;
              justify-content: space-between;
              align-items: center;
              color: #909399;
              font-size: 12px;

              .actions {
                display: flex;
                gap: 10px;
              }
            }
          }
        }
      }
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}

.user-info {
  color: #909399;
  font-size: 12px;
  margin-left: 8px;
}
</style> 